import 'dart:async';
import 'dart:convert';

import 'package:animated_text_kit/animated_text_kit.dart';
import 'package:chatgreat/bloc/version_bloc.dart';
import 'package:chatgreat/helper/AppUtil.dart';
import 'package:chatgreat/helper/helper.dart';
import 'package:chatgreat/helper/my_widget.dart';
import 'package:chatgreat/page/component/background_container.dart';
import 'package:chatgreat/page/component/dialog.dart';
import 'package:chatgreat/page/component/theme/custom_theme.dart';
import 'package:chatgreat/repo/api_server.dart';
import 'package:chatgreat/repo/settings_repo.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_easy_animations/flutter_easy_animations.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_native_splash/flutter_native_splash.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_udid/flutter_udid.dart';
import 'package:get/get.dart';
// import 'package:fluwx/fluwx.dart';
import 'package:go_router/go_router.dart';
import 'package:sign_in_with_apple/sign_in_with_apple.dart';
import 'package:chatgreat/helper/http.dart';
import 'package:url_launcher/url_launcher.dart';

import '../../helper/ability.dart';
import '../../helper/constant.dart';

class SignInScreen extends StatefulWidget {
  final SettingRepository settings;
  final String? username;

  const SignInScreen({super.key, required this.settings, this.username});

  @override
  State<SignInScreen> createState() => _SignInScreenState();
}

class _SignInScreenState extends State<SignInScreen>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;

  @override
  void initState() {
    _controller = AnimationController(
      duration: const Duration(seconds: 2),
      vsync: this,
    )..repeat(reverse: true);
    super.initState();
    context.read<VersionBloc>().add(VersionCheckEvent());

    FlutterNativeSplash.remove();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    var customColors = Theme.of(context).extension<CustomColors>()!;

    return Scaffold(
      body: BackgroundContainer(
        setting: widget.settings,
        enabled: false,
        child: Container(
          decoration: const BoxDecoration(
            image: DecorationImage(
              image: AssetImage('images/bg1.png'),
              fit: BoxFit.fill,
            ),
          ),
          child: Column(
            children: <Widget>[
              ScaleTransition(
                scale: Tween<double>(begin: 1.0, end: 1.06).animate(
                  CurvedAnimation(parent: _controller, curve: Curves.easeInOut),
                ),
                child: Container(
                  margin: EdgeInsets.only(top: 144.w),
                  child: Image.asset('images/login_chat_icon.png',
                      fit: BoxFit.cover),
                ),
              ),
              const SizedBox(height: 25),
              MyTextWeight('Chat4o', 20, Colors.white, FontWeight.w500)
                  .animate()
                  // .shimmer(
                  //     delay: 1000.ms,
                  //     duration: 2000.ms,
                  //     color: customColors.themeBlueColor)
                  // .animate() // this wraps the previous Animate in another Animate
                  .fadeIn(duration: 1200.ms, curve: Curves.easeOutQuad)
                  .slide(),
              const Expanded(child: Text('')),
              // 登录按钮
              Container(
                height: 45,
                width: double.infinity,
                margin: const EdgeInsets.only(left: 38, right: 38, bottom: 148),
                decoration: const BoxDecoration(
                  image: DecorationImage(
                    image: AssetImage('images/guide_button.png'),
                    fit: BoxFit.fill,
                  ),
                ),
                child: TextButton(
                  onPressed: onSigninSubmit,
                  child: const Text(
                    '一键登录',
                    style: TextStyle(color: Colors.white, fontSize: 16),
                  ),
                ),
              )
                  .animate()
                  .fadeIn(duration: 1200.ms, curve: Curves.easeOutQuad)
                  .slide(),
            ],
          ),
        ),
      ),
    );
  }

  Future<void> onSigninSubmit() async {
    String udid = await FlutterUdid.consistentUdid;

    EasyLoading.show(status: '登录中...');
    APIServer().visitorLogin(udid: udid).then((resp) async {
      EasyLoading.dismiss();
      AppUtil().touristLoginModel = resp;
      AppUtil().setLogin(true);
      await widget.settings.set(settingAPIServerToken, resp.token ?? '');
      await widget.settings.set(settingUserInfo, jsonEncode(resp));

      if ((resp.isVip ?? 0) == 1) {
        context.go(Ability().homeRoute);
      } else {
        // 新用户注册后首次进入APP拉起VIP
        context.pushReplacement('/payment');
      }
    }).catchError((e) {
      EasyLoading.dismiss();
      showErrorMessage(resolveError(context, e));
    });
  }
}
